package com.gjs.sso.config.security.image;

import com.gjs.common.enums.ImageValidateCodeEnum;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 图形验证码拦截器
 *
 * @author hejincheng
 */
public class ImageValidateCodeFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 先获取session中的验证码
        String sessionCode = (String) request.getSession().getAttribute(ImageValidateCodeEnum.LOGIN_IMG_VALID_CODE.toString());
        // 获取用户输入的验证码
        String inputCode = request.getParameter("imgValidCode");
        // 判断验证码是否正确
        if(StringUtils.isEmpty(inputCode) || !inputCode.equalsIgnoreCase(sessionCode)){
            throw new BadCredentialsException("图形验证码错误");
        }

        return super.attemptAuthentication(request,response);
    }
}